<?php

/**
 * 主题管理
 */
namespace app\topics\model;

use app\system\model\SystemModel;

class TopicsTagsModel extends SystemModel {

    protected $infoModel = [
        'pri' => 'tags_id',
        'validate' => [
            'name' => [
                'len' => ['1, 50', '话题名称只能为1~50个字符', 'must', 'all'],
            ],
        ],
        'format' => [
            'name' => [
                'function' => ['html_clear', 'all'],
            ]

        ],
        'into' => 'name',
        'out' => '',
    ];

    public function loadList($where = array(), $limit = 0, $order = '') {
        $list = parent::loadList($where, $limit, $order);
        foreach ($list as $key => $vo) {
            $list[$key]['url'] = url('index/Index/index', ['tag' => $vo['name']]);
        }
        return $list;
    }


    /**
     * 添加话题标签
     * @param $tags
     * @param $detailId
     * @return bool
     */
    public function addTags($tags, $detailId) {
        $tagsList = explode(',', $tags);
        $tagsList = array_filter($tagsList);
        $tagsList = array_slice($tagsList, 0, 6);
        if (empty($tagsList)) {
            return true;
        }
        foreach ($tagsList as $vo) {
            $vo = \dux\lib\Str::symbolClear($vo);
            $vo = strtolower($vo);
            $info = $this->getWhereInfo([
                'name' => $vo
            ]);
            if (empty($info)) {
                $status = $this->add([
                    'name' => $vo,
                    'detail_ids' => $detailId,
                    'update_time' => time(),
                    'quote' => 1
                ]);
                if (!$status) {
                    return false;
                }
            } else {
                if (in_array($detailId, explode(',', $info['detail_ids']))) {
                    continue;
                }
                $status = $this->edit([
                    'tags_id' => $info['tags_id'],
                    'detail_ids' => $info['detail_ids'] . ',' . $detailId,
                    'update_time' => time(),
                    'quote' => $info['quote'] + 1
                ]);
                if (!$status) {
                    return false;
                }
            }
        }
        return true;
    }


}